package com.huluobo.a2308douyindemo.shop

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.huluobo.a2308douyindemo.R
import com.huluobo.a2308douyindemo.adapter.CommonPagerAdapter
import com.huluobo.a2308douyindemo.bean.GoodsBean
import com.huluobo.a2308douyindemo.databinding.ActivityDetailBinding
import com.huluobo.a2308douyindemo.mvvm.BaseActivity
import com.huluobo.a2308douyindemo.net.Const
import com.huluobo.a2308douyindemo.utils.MyToast
import dagger.hilt.android.AndroidEntryPoint

/**
 * tabLayout的标题实体类
 */
data class TabEntity(val title: String, val selectIcon: Int = 0, val unSelectIcon: Int = 0) : CustomTabEntity {
    override fun getTabTitle(): String = title

    override fun getTabSelectedIcon(): Int = selectIcon

    override fun getTabUnselectedIcon(): Int = unSelectIcon
}

@AndroidEntryPoint
class DetailActivity : BaseActivity<ActivityDetailBinding, ShopViewModel>() {
    //tab的title数据源
    private val tabEntities = arrayListOf<CustomTabEntity>()

    //通用的vp2的adapter
    private lateinit var commonPagerAdapter: CommonPagerAdapter

    //fragment数据源
    private val fragments = listOf(DetailFragment(), CommentFragment())
    override fun initData() {
        vm.getGoodsDetailSuccess.observe(this) {
            //直接使用DataBinding给页面bean赋值
            binding.goods = it.data
        }

        vm.addToCartSuccess.observe(this) {
            MyToast.showLong("添加购物车成功")
        }
    }

    override fun initView() {
        val goodsId = intent.getIntExtra(Const.KEY_GOODS_ID, 0)
        vm.getGoodsDetail(goodsId)

        tabEntities.clear()
        tabEntities.add(TabEntity("详情"))
        tabEntities.add(TabEntity("评论"))
        binding.detailTabLayout.setTabData(tabEntities)

        commonPagerAdapter = CommonPagerAdapter(this, fragments)
        binding.detailVp2.adapter = commonPagerAdapter

        //tabLayout和vp2的联动
        binding.detailTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                binding.detailVp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        binding.detailVp2.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.detailTabLayout.currentTab = position
            }
        })

        binding.detailAddCart.setOnClickListener {
            val map = mapOf(
                Const.PARAM_GOODS_ID to goodsId,
                Const.PARAM_COUNT to 1
            )
            vm.addToCart(map)
        }

        binding.detailToCart.setOnClickListener {
            startAct(CartActivity::class.java)
        }
    }
}